package cn.fx.basic.util;

import cn.fx.basic.jwt.JwtUtils;
import cn.fx.basic.jwt.Payload;
import cn.fx.basic.jwt.RsaUtils;
import cn.fx.user.domain.LoginData;
import cn.fx.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    /**
     * 返回一个当前登录人信息 logininfo
     */
    public static Logininfo getLogininfo(HttpServletRequest request) throws Exception {

        try {
            //获取请求头中的token
            String token = request.getHeader("token");
            //存在
            if (token != null) {
                //解密 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //将jwtToken解析成想要的数据：loginData
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);

                //判断payload是否为空
                if (payload != null) {
                    //返回一个登录人信息
                    return payload.getLoginData().getLogininfo();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}